from django.http import HttpResponse


class CorsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 拦截请求前处理
        if request.method == "OPTIONS":
            # 直接构造响应对象，避免进入后续中间件和视图
            response = HttpResponse()
            response["Access-Control-Allow-Origin"] = "*"  # 允许所有域，生产环境应指定域名
            response["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
            response["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
            response["Access-Control-Max-Age"] = "86400"  # 预检缓存时间（秒）
            return response

        response = self.get_response(request)
        return response
